<?php
namespace app\store\controller;

use app\common\controller\StoreBase;
use app\store\model\Store;
use think\facade\Cache;

use app\store\model\StoreGroup;
use app\store\model\StoreRule;
use app\store\model\StoreAuth;
use app\store\model\User as UserModel;

class User extends StoreBase
{
    /**
     * 不需要验证权限的模块
     * @var string[]
     */
    protected $noAuth = ['edit_password','edit_mobile'];

    /**
     * 用户列表
     * @return mixed
     */
    public function index()
    {
        return $this->fetch('index');
    }
    public function index_json($limit='',$group_id='')
    {
        $user = new UserModel();
        if($group_id){
            $user = $user->where('group_id',$group_id);
        }
        $list = $user->with('group')->where('id','in', my_auth())->order('sort_order desc,id desc')->paginate($limit);
        $this->result($list);
    }

    /**
     * 新增用户
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['store_id'] = StoreId();
            $param['is_verify'] = '1';
            $verify = input('_verify', true);
            //验证规则
            if($verify!='0'){
                try{
                    $this->validate($param, 'user');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            $result = UserModel::create($param);
            if ($result == true) {
                clear_store_cache();//清空整个商户的缓存
                insert_user_log('添加了员工');
                $this->success('添加成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        $user = UserModel::with('group')->where('id',UserId())->find();
        return $this->fetch('save', [
            'user_rule'  => StoreRule::list_to_level(),
            'user_group' => list_to_level(StoreGroup::get_list(),$user['pid'])
        ]);
    }

    /**
     * 修改用户
     * @param $id 编辑
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit($id)
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            if (empty($param['password'])) {
                unset($param['password']);
            }
            $verify = input('_verify', true);
            //验证规则
            if($verify!='0'){
                try{
                    $this->validate($param, 'user');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            //检查手机号码是否修改
            $phone = UserModel::where('id',$param['id'])->value('mobile');
            if(isset($param['mobile']) && $param['mobile'] != $phone){
                $param['is_verify'] = 0;
            }
            //更新数据
            $resule = UserModel::update($param,['id'=>$param['id']]);
            if ( $resule == true) {
                clear_store_cache();//清空整个商户的缓存
                insert_user_log('修改了员工信息');
                $this->success('修改成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        $data = UserModel::where('id', $id)->find();
        $user = UserModel::with('group')->where('id',UserId())->find();
        return $this->fetch('save', [
            'data'       => $data,
            'user_rule'  => StoreRule::list_to_level(),
            'user_group' => list_to_level(StoreGroup::get_list(),$user['pid'])
        ]);
    }

    /**
     * 删除用户
     */
    public function del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //判断是否主管理员
            $store = \app\store\model\Store::where('id',StoreId())->cache('store_info'.StoreId(),86400,'store'.StoreId())->find();
            if($store['admin_id'] == $param['id']){
                $this->error('主管理员不允许删除');
            }else{
                UserModel::destroy($param['id'],true);
                clear_store_cache();//清空整个商户的缓存
                insert_user_log('删除了用户组');
                $this->success('删除成功');
            }
        }
    }
    
    public function edit_password()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            // 验证条件
            empty($param['password']) && $this->error('请输入旧密码');
            empty($param['new_password']) && $this->error('请输入新密码');
            empty($param['rep_password']) && $this->error('请输入确认密码');
            !check_password($param['new_password'], 6, 16) && $this->error('请输入6-16位的密码');
            $param['new_password'] != $param['rep_password'] && $this->error('两次密码不一致');
            $admin = UserModel::where('id', UserId())->find();
            $admin['password'] != md5($param['password']) && $this->error('旧密码错误');
            $data = ['password' => $param['new_password']];
            $result = UserModel::update($data,['id'=> UserId()]);
            if ($result == true) {
                insert_user_log('修改了登录密码');
                session('user_auth', null);
                session('user_auth_sign', null);
                $this->success('更新成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        return $this->fetch('edit_password');
    }

    /**
     * 修改手机号码
     * @param $mobile 手机号码
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit_mobile($mobile)
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            // 验证条件
            empty($param['password']) && $this->error('请输入旧密码');
            empty($param['new_password']) && $this->error('请输入新密码');
            empty($param['rep_password']) && $this->error('请输入确认密码');
            !check_password($param['new_password'], 6, 16) && $this->error('请输入6-16位的密码');
            $param['new_password'] != $param['rep_password'] && $this->error('两次密码不一致');
            $admin = UserModel::where('id', UserId())->find();
            $admin['password'] != md5($param['password']) && $this->error('旧密码错误');
            $data = ['password' => $param['new_password']];
            $result = UserModel::update($data,['id'=> UserId()]);
            if ($result == true) {
                insert_user_log('修改了登录手机号码');
                session('user_auth', null);
                session('user_auth_sign', null);
                $this->success('更新成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        return $this->fetch('edit_mobile');
    }
    
    
}